/*
 *    Copyright (c) 2018-2025, lengleng All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: lengleng (wangiegie@gmail.com)
 */
package com.pig4cloud.pig.mt.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.pig4cloud.pig.mt.common.api.utils.Query;
import com.pig4cloud.pig.mt.entity.WxAccount;
import com.pig4cloud.pig.mt.mapper.WxAccountMapper;
import com.pig4cloud.pig.mt.service.WxAccountService;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.config.WxMpConfigStorage;
import me.chanjar.weixin.mp.config.impl.WxMpDefaultConfigImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;
import java.io.Serializable;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 公众号账号
 *
 * @author JLM
 * @date 2021-03-05 11:45:09
 */
@Slf4j
@Service
public class WxAccountServiceImpl extends ServiceImpl<WxAccountMapper, WxAccount> implements WxAccountService {
	@Autowired
	WxMpService wxMpService;

	@Override
	public IPage queryPage(Map<String, Object> params) {
		String name = (String) params.get("name");
		IPage<WxAccount> page = this.page(
				new Query<WxAccount>().getPage(params),
				new QueryWrapper<WxAccount>()
						.like(!StringUtils.isEmpty(name), "name", name)
		);

		return page;
	}

	@PostConstruct
	public void loadWxMpConfigStorages() {
		log.info("加载公众号配置...");
		List<WxAccount> accountList = this.list();
		if (accountList == null || accountList.isEmpty()) {
			log.info("未读取到公众号配置，请在管理后台添加");
			return;
		}
		log.info("加载到{}条公众号配置", accountList.size());
		accountList.forEach(this::addAccountToRuntime);
		log.info("公众号配置加载完成");
	}

	@Override
	public boolean save(WxAccount entity) {
		Assert.notNull(entity, "WxAccount不得为空");
		String appid = entity.getAppid();
		if (this.isAccountInRuntime(appid)) { //已有此appid信息，更新
			log.info("更新公众号配置");
			wxMpService.removeConfigStorage(appid);
			this.addAccountToRuntime(entity);

			return SqlHelper.retBool(this.baseMapper.updateById(entity));
		} else {//已有此appid信息，新增
			log.info("新增公众号配置");
			this.addAccountToRuntime(entity);

			return SqlHelper.retBool(this.baseMapper.insert(entity));
		}

	}

	@Override
	public boolean removeByIds(Collection<? extends Serializable> idList) {
		Assert.notEmpty(idList, "WxAccount不得为空");

		// 更新wxMpService配置
		log.info("同步移除公众号配置");
		idList.forEach(id -> wxMpService.removeConfigStorage((String) id));

		return SqlHelper.retBool(this.baseMapper.deleteBatchIds(idList));
	}

	/**
	 * 判断当前账号是存在
	 *
	 * @param appid
	 * @return
	 */
	private boolean isAccountInRuntime(String appid) {
		try {
			return wxMpService.switchover(appid);
		} catch (NullPointerException e) {// sdk bug，未添加任何账号时configStorageMap为null会出错
			return false;
		}
	}

	/**
	 * 添加账号到当前程序，如首次添加需初始化configStorageMap
	 *
	 * @param entity
	 */
	private synchronized void addAccountToRuntime(WxAccount entity) {
		String appid = entity.getAppid();
		WxMpDefaultConfigImpl config = entity.toWxMpConfigStorage();
		try {
			wxMpService.addConfigStorage(appid, config);//这里把配置文件里的覆盖了
		} catch (NullPointerException e) {
			log.info("需初始化configStorageMap...");
			Map<String, WxMpConfigStorage> configStorages = new HashMap<>(4);
			configStorages.put(appid, config);
			wxMpService.setMultiConfigStorages(configStorages, appid);
		}
	}
}
